package bit.dao;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import bit.dao.BoardDTO;

public class BoardDAO {
	private SqlSessionFactory sqlMapper;
	
	public BoardDAO(){
		String resource = "bit/mybatis/SqlMapConfig.xml";
		try {
			InputStream is = Resources.getResourceAsStream(resource);
			sqlMapper = new SqlSessionFactoryBuilder().build(is);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public int boardWrite(BoardDTO dto) {
		SqlSession session = sqlMapper.openSession();
		int cnt=0;
		try {
			cnt = session.insert("boardWrite", dto);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			session.close();
		}
		return cnt;
	}

	public List<BoardDTO> boardList() {
		List<BoardDTO> list = new ArrayList<BoardDTO>();
		SqlSession session = sqlMapper.openSession();
		try {
			list = session.selectList("boardList");
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			session.close();
		}
		return list;
	}

	public BoardDTO boardDetail(String num) {
		BoardDTO dto = new BoardDTO();
		SqlSession session = sqlMapper.openSession();
		try {
			dto = session.selectOne("boardDetail", new Integer(num));
			session.commit();
		} catch (Exception e) { 
			e.printStackTrace(); 
		} finally{
			session.close();
		}
		return dto;
	}

	public int boardDelete(String num) {
		int cnt=0;
		SqlSession session = sqlMapper.openSession();
		try {
			cnt = session.delete("boardDelete", new Integer(num));
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			session.close();
		}
		return cnt;
	}

	public int boardUpdate(BoardDTO dto) {
		int cnt = 0;
		SqlSession session = sqlMapper.openSession();
		try {
			cnt = session.update("boardUpdate", dto);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			session.close();
		}
		return cnt;
	}

}
